const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const path = require("path");
const multer = require("multer");
const fs = require("fs");

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
	cors: {
		origin: "*",
		methods: ["GET", "POST"],
	},
});

const PORT = 3000;
const users = new Set();

// 配置文件上传
const storage = multer.diskStorage({
	destination: (req, file, cb) => {
		cb(null, "public/uploads/");
	},
	filename: (req, file, cb) => {
		const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
		cb(null, uniqueSuffix + path.extname(file.originalname));
	},
});

const upload = multer({
	storage,
	limits: { fileSize: 5 * 1024 * 1024 }, // 限制5MB
	fileFilter: (req, file, cb) => {
		const allowedTypes = ["image/jpeg", "image/png", "image/gif"];
		if (allowedTypes.includes(file.mimetype)) {
			cb(null, true);
		} else {
			cb(new Error("只允许上传图片文件"));
		}
	},
});

// 确保上传目录存在
const uploadsDir = path.join(__dirname, "public/uploads");
if (!fs.existsSync(uploadsDir)) {
	fs.mkdirSync(uploadsDir, { recursive: true });
}

// 文件上传路由
app.post("/upload", upload.single("image"), (req, res) => {
	if (!req.file) {
		return res.status(400).json({ error: "未选择文件" });
	}
	res.json({
		url: `/uploads/${req.file.filename}`,
		originalName: req.file.originalname,
	});
});

// 静态文件服务
app.use(express.static("public"));

// Socket.io连接处理
io.on("connection", (socket) => {
	console.log("新用户连接");

	// 处理用户名设置
	socket.on("set username", (username, callback) => {
		if (users.has(username)) {
			callback({ success: false, message: "用户名已存在" });
		} else {
			users.add(username);
			socket.username = username;

			socket.broadcast.emit("user joined", username);
			socket.emit("welcome", `欢迎加入聊天室，${username}!`);
			io.emit("update users", Array.from(users));

			callback({ success: true });
		}
	});

	// 处理消息发送
	socket.on("chat message", (data) => {
		if (socket.username) {
			const messageData = {
				user: socket.username,
				message: data.message,
				isCurrentUser: false,
				isImage: data.isImage || false,
				imageUrl: data.imageUrl || null,
				timestamp: new Date().toLocaleTimeString(),
			};

			socket.broadcast.emit("chat message", messageData);
			socket.emit("chat message", {
				...messageData,
				isCurrentUser: true,
			});
		}
	});

	// 处理断开连接
	socket.on("disconnect", () => {
		if (socket.username) {
			users.delete(socket.username);
			io.emit("user left", socket.username);
			io.emit("update users", Array.from(users));
		}
		console.log("用户断开连接");
	});
});

server.listen(PORT, () => {
	console.log(`服务器运行在 http://localhost:${PORT}`);
});
